package com.example.application.views.store;

import com.example.application.bean.*;
import com.example.application.views.main.MainView;
import com.example.application.views.pet.PetUrl;
import com.example.application.views.pet.PetView;
import com.example.application.views.petSupplier.PetSupplierUri;
import com.example.application.views.petSupplier.PetSupplierView;
import com.example.application.views.util.DialogUtil;
import com.example.application.views.util.MapToJsonUtil;
import com.example.application.views.util.MyHttpClientUtil;
import com.example.application.views.util.ShowAllInfosUtil;
import com.example.page.PageComponent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vaadin.flow.component.Text;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.crud.BinderCrudEditor;
import com.vaadin.flow.component.crud.Crud;
import com.vaadin.flow.component.crud.CrudEditor;
import com.vaadin.flow.component.datepicker.DatePicker;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.gridpro.GridPro;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.splitlayout.SplitLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.data.converter.StringToDoubleConverter;
import com.vaadin.flow.router.Route;

import java.util.HashMap;
import java.util.Map;

@Route(value = "stoGoods", layout = MainView.class)
public class StoGoodsView extends Div {

    private GridPro<StoGoods> grid = new GridPro<>();
    private Crud<StoGoods> crud = new Crud<StoGoods>(StoGoods.class, grid, createSupGoodsEditor());

    private int curPage = 1;
    private int pageSize = 2;
    private int tolNum;
    private int tolPage;

    private Map<String,Object> condition = new HashMap<>();

    private PageBean<StoGoods> pageBean = null;

    private ObjectMapper mapper = new ObjectMapper();

    private StoGoods stoGoods;

    private TextField name;
    private TextField type;
    private TextField material;
    private TextField applicable;
    private TextField exclusive;
    private TextField packingSize;
    private TextField flavor;
    private TextField function;
    private TextField origin;
    private DatePicker dateOfPro;
    private TextField expDate;
    private TextField explain;
    private TextField price;
    private TextField pic;

    private User user = null;

    private Store store = null;

    public StoGoodsView(){
        user = (User) UI.getCurrent().getSession().getAttribute("user");
        store = (Store) UI.getCurrent().getSession().getAttribute("store");

        if (user == null){

        }else if(store == null){
            Dialog dialog = new Dialog();
            dialog.setCloseOnEsc(false);
            dialog.setCloseOnOutsideClick(false);
            dialog.removeAll();
            dialog.add(new Text("请先选择门店"));

            Button okBtn = new Button("去选择门店", sure ->{
//           跳转到门店管理界面
                UI.getCurrent().navigate("store");
                dialog.close();
            });

            dialog.add(new Div(okBtn, new Text("      ")));
            dialog.open();
        }else if("门店管理员".equals(user.getIdentity())){
            //在最下面
            this.init();
        }else{
            DialogUtil.adminAuthority();
        }

    }

    private CrudEditor<StoGoods> createSupGoodsEditor() {
        name = new TextField("商品名");
        type = new TextField("种类");
        material = new TextField("材质");
        applicable = new TextField("适用规格");
        exclusive = new TextField("专属规格");
        packingSize = new TextField("包装规格");
        flavor = new TextField("口味");
        function = new TextField("特殊功用");
        origin = new TextField("产地");
        dateOfPro = new DatePicker("出厂日期");
        expDate = new TextField("保质期");
        explain = new TextField("特色说明");
        price = new TextField("价格");
        pic = new TextField("图片");
        FormLayout form = new FormLayout(name, type, material, applicable, exclusive, packingSize, flavor, function, origin, dateOfPro, expDate, explain, price, pic);

        Binder<StoGoods> binder = new Binder<>(StoGoods.class);
        binder.bind(name, StoGoods::getName, StoGoods::setName);
        binder.bind(type, StoGoods::getType, StoGoods::setType);
        binder.bind(material, StoGoods::getMaterial, StoGoods::setMaterial);
        binder.bind(applicable, StoGoods::getApplicable, StoGoods::setApplicable);
        binder.bind(exclusive, StoGoods::getExclusive, StoGoods::setExclusive);
        binder.bind(packingSize, StoGoods::getPackingSize, StoGoods::setPackingSize);
        binder.bind(flavor, StoGoods::getFlavor, StoGoods::setFlavor);
        binder.bind(function, StoGoods::getFunction, StoGoods::setFunction);
        binder.bind(origin, StoGoods::getOrigin, StoGoods::setOrigin);
        binder.bind(dateOfPro, StoGoods::getDateOfPro, StoGoods::setDateOfPro);
        binder.bind(expDate, StoGoods::getExpDate, StoGoods::setExpDate);
        binder.bind(explain, StoGoods::getExplain, StoGoods::setExplain);
        binder.forField(price).withConverter(new StringToDoubleConverter("请输入数字")).bind("price");
        binder.bind(pic, StoGoods::getPic, StoGoods::setPic);

        return new BinderCrudEditor<>(binder, form);
    }




    private void createGridLayout(SplitLayout splitLayout) {
        Div wrapper = new Div();
        wrapper.setId("grid-wrapper");
        wrapper.setWidthFull();
        PageComponent pageComponent = new PageComponent(curPage, pageSize, StoGoodsView.this.tolNum, StoGoodsView.this.tolPage) {
            @Override
            protected void pageNext() {
                StoGoodsView.this.curPage = this.curPage;
                updateForm();
            }

            @Override
            protected void pagePrevious() {
                StoGoodsView.this.curPage = this.curPage;
                updateForm();
            }

            @Override
            protected void gotoPage() {
                StoGoodsView.this.curPage = this.curPage;
                updateForm();
            }

            @Override
            protected void firstPage() {
                StoGoodsView.this.curPage = 1;
                updateForm();
            }

            @Override
            protected void lastPage() {
                StoGoodsView.this.curPage = this.tolPage;
                updateForm();
            }

            @Override
            protected void selectPage() {
                StoGoodsView.this.pageSize = pageSize;
                updateForm();
            }
        };
        pageComponent.components.add(crud);
        pageComponent.init();
        splitLayout.addToPrimary(pageComponent);
    }




    private void editItem(){
        name.setEnabled(false);
        type.setEnabled(false);
        material.setEnabled(false);
        applicable.setEnabled(false);
        exclusive.setEnabled(false);
        packingSize.setEnabled(false);
        flavor.setEnabled(false);
        function.setEnabled(false);
        origin.setEnabled(false);
        dateOfPro.setEnabled(false);
        expDate.setEnabled(false);
    }

    private void addItem(){
        name.setEnabled(true);
        type.setEnabled(true);
        material.setEnabled(true);
        applicable.setEnabled(true);
        exclusive.setEnabled(true);
        packingSize.setEnabled(true);
        flavor.setEnabled(true);
        function.setEnabled(true);
        origin.setEnabled(true);
        dateOfPro.setEnabled(true);
        expDate.setEnabled(true);
    }

    public void init(){
        SplitLayout splitLayout = new SplitLayout();
        splitLayout.setSizeFull();
        updateForm();
        createGridLayout(splitLayout);

        Crud.addEditColumn(grid);

        HorizontalLayout horizontalLayout = new HorizontalLayout();
        Button button = new Button("查看统计");
        button.addClickListener((e) -> {
            UI.getCurrent().navigate("count");
        });
        horizontalLayout.add(button);
        HorizontalLayout layout = new HorizontalLayout();

        grid.addColumn(StoGoods::getName).setHeader("商品名");
        grid.addColumn(StoGoods::getType).setHeader("类型");
        grid.addColumn(StoGoods::getMaterial).setHeader("材质");
        grid.addColumn(StoGoods::getApplicable).setHeader("适用规格");
        grid.addColumn(StoGoods::getExclusive).setHeader("专属规格");
        grid.addColumn(StoGoods::getPackingSize).setHeader("包装规格");
        grid.addColumn(StoGoods::getFlavor).setHeader("口味");
        grid.addColumn(StoGoods::getFunction).setHeader("特殊功用");
        grid.addColumn(StoGoods::getOrigin).setHeader("产地");
        grid.addColumn(StoGoods::getDateOfPro).setHeader("生产日期");
        grid.addColumn(StoGoods::getExpDate).setHeader("保质期");
        // grid.addColumn(StoGoods::getSupId).setHeader("供货商ID");
        grid.addEditColumn(StoGoods::getExplain).text(StoGoods::setExplain).setHeader("特色说明");
        grid.addEditColumn(StoGoods::getPrice).text((item, newValue)->{
            item.setPrice(Double.parseDouble(newValue));
        }).setHeader("价格");
        grid.addEditColumn(StoGoods::getPic).text(StoGoods::setPic).setHeader("图片");

        layout.add(crud);
        this.add(horizontalLayout, layout);
        add(splitLayout);

        crud.addEditListener(e -> {
            editItem();
        });

        crud.addNewListener(e -> {
//                addItem();
            UI.getCurrent().navigate("supGoods");
        });

        //增删改查
        crud.addSaveListener(e -> {
            stoGoods = e.getItem();

            // 修改----修改----修改
            if(stoGoods.getId() != null){
                try {
                    stoGoods.setExplain(explain.getValue());
                    stoGoods.setPrice(Double.parseDouble(price.getValue()));
                    stoGoods.setPic(pic.getValue());

                    String json = MyHttpClientUtil.httpPut(StoGoodsUrl.STOGOODS_UPDATE, stoGoods, "utf-8");
                    JavaType javaType = mapper.getTypeFactory().constructParametricType(ResultBean.class, StoGoods.class);
                    ResultBean resultBean = mapper.readValue(json, javaType);

                    if(resultBean.getCode() != 0){
                        UI.getCurrent().getPage().executeJs("alert('更新成功');");
                        updateForm();
                    }else {
                        UI.getCurrent().getPage().executeJs("alert('更新失败')");
                    }

                }catch (Exception exception){
                    exception.printStackTrace();
                }

                // 添加
            }else {
                try {
                    stoGoods.setName(name.getValue());
                    stoGoods.setType(type.getValue());
                    stoGoods.setMaterial(material.getValue());
                    stoGoods.setApplicable(applicable.getValue());
                    stoGoods.setExclusive(exclusive.getValue());
                    stoGoods.setPackingSize(packingSize.getValue());
                    stoGoods.setFlavor(flavor.getValue());
                    stoGoods.setFunction(function.getValue());
                    stoGoods.setOrigin(origin.getValue());
                    stoGoods.setDateOfPro(dateOfPro.getValue());
                    stoGoods.setExpDate(expDate.getValue());
                    // stoGoods.setSupId(5);
                    stoGoods.setExplain(explain.getValue());
                    stoGoods.setPrice(Double.parseDouble(price.getValue()));
                    stoGoods.setPic(pic.getValue());

                    Store store = new Store();
                    store.setId(user.getId());
                    stoGoods.setStore(store);

                    String json = MyHttpClientUtil.httpPost(StoGoodsUrl.STOGOODS_ADD, stoGoods, "utf-8");
                    JavaType javaType = mapper.getTypeFactory().constructParametricType(ResultBean.class, StoGoods.class);
                    ResultBean resultBean = mapper.readValue(json, javaType);

                    if(resultBean.getCode() != 0){
                        UI.getCurrent().getPage().executeJs("alert('添加成功');");
                        // 刷新界面
                        updateForm();
                    }else {
                        UI.getCurrent().getPage().executeJs("alert('添加失败')");
                    }
                }catch (Exception exception){
                    exception.printStackTrace();
                }

            }
        });

        // 删除
        crud.addDeleteListener(e -> {
            stoGoods = e.getItem();
            try {
                if(stoGoods.getId() != null){
                    String msg = MyHttpClientUtil.httpDelete(StoGoodsUrl.STOGOODS_DELETE, stoGoods.getId(), "utf-8");
                    ResultBean resultBean = mapper.readValue(msg, ResultBean.class);
                    if(resultBean.getCode() != 0){
                        // 此处url要改成自己的后台接口的url
                        UI.getCurrent().getPage().executeJs("alert('删除成功');");
                        updateForm();
                    }else {
                        UI.getCurrent().getPage().executeJs("alert('删除失败');");
                    }
                }
            }catch (Exception exception){
                exception.printStackTrace();
            }

        });

    }


    private void updateForm(){
        String url = StoGoodsUrl.STOGOODS_SHOWALL;
        condition.put("currentPage", StoGoodsView.this.curPage);
        condition.put("pageSize",StoGoodsView.this.pageSize);
        condition.put("id",store.getId());

        url= MapToJsonUtil.getUrl(condition,url);
        String json = MyHttpClientUtil.HttpGet(url, null);
        ObjectMapper objectMapper = new ObjectMapper();
        ResultBean<PageBean<StoGoods>> resultBean=null;

        try {
            resultBean = objectMapper.readValue(json, new TypeReference<ResultBean<PageBean<StoGoods>>>() { });
            pageBean = resultBean.getT();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        grid.setItems(pageBean.getDatas());

        tolNum = pageBean.getTolNum();
        tolPage = pageBean.getTolPage();
        pageSize = pageBean.getPageSize();
        curPage = pageBean.getCurrentPage();
    }
}
